<?php
namespace app\api\controller\vppz;


use think\Cache;


use \app\admin\model\vppz\Kangyang as KangyangModel;

use \addons\vppz\library\Vpower;

class Kangyang extends App
{
    protected $noNeedLogin = ['*'];
    protected $noNeedRight = ['*'];

    public function _initialize(){
        parent::_initialize();
        $this->KangyangModel = new KangyangModel;
        $this->model = new \app\admin\model\vppz\HealthPackage;
        $this->service_model = new \app\admin\model\vppz\HealthService;
        $this->relationmodel = new \app\admin\model\vppz\PackageService;
        $this->ordermodel = new \app\admin\model\vppz\ServiceOrder;
        $this->detailmodel = new \app\admin\model\vppz\OrderServiceDetail;
        $this->Communitymodel = new \app\admin\model\vppz\Community;
    }


    /**
     * 服务下单页
     */
    public function kangyanglists(){
		$area=$this->_area;
        $type = input('type',1);
        $kangyang = $this->KangyangModel->where('type','=',$type)->order(['weigh'=>'DESC','createtime'=>'desc'])->select();
        if(empty($kangyang) === FALSE){
            foreach ($kangyang as $bk=>$bj){
                $kangyang[$bk]['createtime'] = date('Y-m-d H:i:s',$kangyang[$bk]['createtime']);
            }
        }
		$this->success('',array(
			'now'=>time(),
			'kangyang'=>$kangyang
		));
    }

    /**
     * 服务下单页
     */
    public function detail(){

		$id = input('id');

		$kangyang = $this->KangyangModel->find($id);
		if(empty($kangyang)){
			$this->error('不存在或暂停提供');
		}
        $kangyang['createtime'] = date('Y-m-d H:i:s',$kangyang['createtime']);
		$this->success('',array(
			'now'=>time(),
			'kangyang'=>$kangyang
		));
    }
    /**
     * 套餐详情
     */
    public function packagedetail(){
        $id = input('id');
        $package = $this->model->find($id);
		if(empty($package)){
			$this->error('不存在或暂停提供');
		}
        if(empty($package['notices'])){
            $package['notices'] = '';
        }
        if($package['show_price'] >0){
            $package['discount'] = sprintf("%.1f",10 * $package['price'] / $package['show_price']);
        }
        //获取服务
        $relation = $this->relationmodel->where([
            'package_id'=>$id
        ])->whereNull('deletetime')->select();
        $service = [];
        if(empty($relation) === FALSE){
            foreach ($relation as &$v){
                $servicedetail = $this->service_model->whereNull('deletetime')->where([
                    'id'=>$v['service_id']
                ])->find();
                $servicedetail['price'] = $v['price'];
                $servicedetail['num'] = $v['num'];
                $servicedetail['duration'] = $v['duration'];
                $service[] = $servicedetail;
            }
        }
        $package['services'] = $service;
		$this->success('',$package);
    }
    //下单
    public function placeorder(){
        $mine = $this->_mine;
        $json = file_get_contents("php://input");
        // 将JSON字符串解码为PHP数组或对象
        $data = json_decode($json, true);
        //查询医生是否绑定用户
        $packageId = '';
        $package = $this->model->where(array(
            'id'=>$data['packageId']
        ))->whereNull('deletetime')->find();
        if(empty($package)){
            $this->error('套餐状态异常，请联系所在社区确认');
        }
        $communityinfo = $this->Communitymodel->where([
            'id'=>$package['community_id']
        ])->find();
        if(empty($communityinfo)){
            $this->error('社区信息有误，请联系所在社区确认');
        }
        //查询服务
        $relation = $this->relationmodel->where([
            'package_id'=>$data['packageId']
        ])->whereNull('deletetime')->select();
//        if(empty($relation)){
//            $this->error('套餐没有包含任何服务项目，请联系所在社区确认');
//        }
        $orderdata = array(
            'app_id'=>$this->app_id,
            'user_id'=>$mine['id'],
            'openid'=>$mine['openid'],
            'area_id'=>$communityinfo['area_id'],
            'community_id'=>$communityinfo['id'],
            'order_no'=>uniqid('order_', true),
            'package_id'=>$data['packageId'],
            'package_name'=>$package['name'],
            'customer_name'=>$data['contactInfo']['name'],
            'customer_phone'=>$data['contactInfo']['phone'],
            'package_price'=>$package['price'],
            'actual_amount'=>$data['price'],
            'special_requirements'=>$data['contactInfo']['remark']
        );
        $this->ordermodel->startTrans();
        $opera = array();
        $opera[]=$this->ordermodel->save($orderdata);
		$order_id = $this->ordermodel->id;

        if(empty($relation) === FALSE){
            foreach ($relation as &$v){
                $service = $this->service_model->where([
                    'id'=>$v['service_id']
                ])->whereNull('deletetime')->find();
                if(empty($service) === FALSE){
                    $orderDetail = array(
                        'order_id'=>$order_id,
                        'service_id'=>$service['id'],
                        'service_name'=>$service['name'],
                        'service_price'=>$v['price'],
                        'service_count'=>$v['num'],
                        'service_duration'=>$v['duration'],
                    );
                    $opera[] = $this->detailmodel->save($orderDetail);
                }
            }
        }



		if(\Tools::checkArrayResult($opera)){
			$this->model->commit();
            $pay_params = \addons\epay\library\Service::submitOrder([
                'amount'=>$orderdata['actual_amount'],
                'type'=>"wechat",
                'orderid'=>'KANGYANG_'.$order_id,
                'title'=>$orderdata['package_name'],
                'notifyurl'=>$this->request->root(true) . '/addons/vppz/pay/notify/paytype/wechat',
                //'returnurl'=>"返回地址",// 小程序前端直接反馈无需返回地址页面
                'method'=>"miniapp",
                'openid'=>$orderdata['openid']
                //'auth_code'=>rand(1000,9999);
            ]);
            $this->success('下单成功',array(
                'order_id'=>$order_id,
                'pay_params'=>$pay_params
            ));
		}else{
            $this->model->rollback();
            $this->error('抱歉，提交失败，重试看看呢');
        }
    }
}
